﻿#region Copyright 2011 Mike Goatly
// This source is subject to the the MIT License (MIT)
// All rights reserved.
#endregion

namespace Lifti.Tests.Persistence.DataFileManagerTests
{
    using System;
    using System.IO;

    using Lifti.Persistence;
    using Lifti.Persistence.IO;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Tests for extending the underlying file using the IO manager.
    /// </summary>
    [TestClass]
    public class Extending : UnitTestBase
    {
        /// <summary>
        /// The path to the test file.
        /// </summary>
        private const string Path = "testindex.dat";

        /// <summary>
        /// Cleans up before and after each test.
        /// </summary>
        [TestCleanup]
        [TestInitialize]
        public void TestCleanup()
        {
            if (File.Exists(Path))
            {
                File.Delete(Path);
            }
        }

        /// <summary>
        /// The underlying file should be extended as requested.
        /// </summary>
        [TestMethod]
        public void ShouldExtendTheLengthOfTheUnderlyingFile()
        {
            using (var writer = File.CreateText(Path))
            {
                writer.Write("Test");
            }

            using (var manager = new DataFileManager(Path))
            {
                manager.ExtendStream(8);
            }

            Assert.AreEqual(8, File.ReadAllBytes(Path).Length);
        }

        /// <summary>
        /// An exception should be thrown if the file is extended to less than its current size.
        /// </summary>
        [TestMethod]
        public void ShouldRaiseExceptionIfRequestedLengthIsLessThanOrEqualToCurrentLength()
        {
            using (var writer = File.CreateText(Path))
            {
                writer.Write("Test");
            }

            using (var manager = new DataFileManager(Path))
            {
                AssertRaisesException<ArgumentException>(() => manager.ExtendStream(4), "Can only extend file beyond its current length.\r\nParameter name: requiredLength");
            }
        }
    }
}
